﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
using Microsoft.Win32;
using System.Reflection;
using System.Diagnostics;
using FCNS.Data;

namespace DoubleH.Utility.Configuration
{
    public sealed class ConfigSerializer
    {
        public static UserConfig LoadUserConfig(Int64 userId)
        {
            UserConfig tConfig = null;
            XmlSerializer xmlSerial = new XmlSerializer(typeof(UserConfig));
            FileStream fs = null;
            //try
            //{
            //fs = new FileStream(AppDefines.appConfigPath + userId.ToString() + ".xml", FileMode.Open, FileAccess.Read);
            //GZipStream compressionStream = new GZipStream(fs, CompressionMode.Decompress);
            //StreamReader reader = new StreamReader(compressionStream);
            //tConfig = (UserConfig)xmlSerial.Deserialize(reader);
            //reader.Dispose();
            //compressionStream.Dispose();
            //}

            try
            {
                fs = new FileStream(FCNS.Data.DbDefine.appConfigDir + userId.ToString() + ".xml", FileMode.Open, FileAccess.Read, FileShare.Read);
                tConfig = (UserConfig)xmlSerial.Deserialize(fs);
                fs.Dispose();
            }
            catch (Exception) { tConfig = new UserConfig(); }
            return tConfig;

            //数据库存储
            //UserConfig tConfig = null;
            //XmlSerializer xmlSerial = new XmlSerializer(typeof(UserConfig));
            //try
            //{
            //    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(FCNS.Data.Table.UserS.LoginUser.UserConfig));
            //    tConfig = (UserConfig)xmlSerial.Deserialize(ms);
            //    ms.Dispose();
            //}
            //catch (Exception) { tConfig = new UserConfig(); }
            //return tConfig;
        }

        public static bool SaveConfig(UserConfig userConfigEx, Int64 userId)
        {
            XmlSerializer xmlSerial = new XmlSerializer(typeof(UserConfig));
            Stream fs = new FileStream(FCNS.Data.DbDefine.appConfigDir + userId.ToString() + ".xml", FileMode.Create);
            //Stream fs = new FileStream(AppDefines.appConfigPath + userId.ToString() + ".xml", FileMode.Create, FileAccess.Write, FileShare.None);
            //GZipStream gz = new GZipStream(fs, CompressionMode.Compress);
            //StreamWriter writer = new StreamWriter(gz);

            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Encoding = Encoding.UTF8;
            xws.Indent = true;
            xws.IndentChars = "\t";

            XmlWriter xw = XmlWriter.Create(fs, xws);
            xmlSerial.Serialize(xw, userConfigEx);
            xw.Flush();
            xw.Close();
            if (fs != null)
            {
                fs.Close(); fs = null;
            }
            return true;

            //XmlSerializer xmlSerial = new XmlSerializer(typeof(UserConfig));
            //MemoryStream ms = new MemoryStream();

            //XmlWriterSettings xws = new XmlWriterSettings();
            //xws.Encoding = new UTF8Encoding(false);
            //xws.Indent = true;
            //xws.IndentChars = "\t";
            //xws.OmitXmlDeclaration = false;

            //XmlWriter xw = XmlWriter.Create(ms, xws);
            //xmlSerial.Serialize(xw, userConfigEx);
            //xw.Close();
            //FCNS.Data.Table.UserS.LoginUser.UserConfig = Encoding.UTF8.GetString(ms.GetBuffer());
            //ms.Dispose();
            //return true;
        }

        public static object LoadConfig(Type t, string file)
        {
            Debug.Assert(t != null, file);
            InitVar();

            object tConfig = null;
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                byte[] by = File.ReadAllBytes(file);
                MemoryStream stream = new MemoryStream(by);
                tConfig = bf.Deserialize(stream);
                stream.Dispose();
                return tConfig;
            }
            catch
            {
                XmlSerializer xmlSerial = new XmlSerializer(t);
                FileStream fs = null;
                try
                {
                    fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
                    tConfig = xmlSerial.Deserialize(fs);
                    fs.Dispose();
                }
                catch
                {
                    return t.Assembly.CreateInstance(t.FullName);
                }
                return tConfig;
            }
        }

        public static bool SaveConfig(object config, string file)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            bf.Serialize(stream, config);
            File.WriteAllBytes(file, stream.ToArray());
            stream.Dispose();
            return true;


            //XmlSerializer xmlSerial = new XmlSerializer(config.GetType());
            //StreamWriter fs = new StreamWriter(file, false, Encoding.UTF8);
            //XmlWriterSettings xws = new XmlWriterSettings();
            //xws.Encoding = Encoding.UTF8;
            //xws.Indent = true;
            //xws.IndentChars = "\t";

            //XmlWriter xw = XmlWriter.Create(fs, xws);
            //xmlSerial.Serialize(xw, config);
            //xw.Close();
            //if (fs != null)
            //{
            //    fs.Close(); fs = null;
            //}
            //return true;
        }

        private static void InitVar()
        {
            try
            {
                CreateDirectory(DbDefine.extensionDir, DbDefine.printDir, DbDefine.updateDir, DbDefine.appConfigDir, DbDefine.posLogDir);
                CreateDirectory(DbDefine.dataDir, DbDefine.dataDir + "GroupS", DbDefine.dataDir + "ProductS", DbDefine.dataDir + "WeiBaoS");

                //隐藏打印的页眉页脚
                RegistryKey pregKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\PageSetup", true);
                if (pregKey != null)
                {
                    pregKey.SetValue("footer", "");
                    pregKey.SetValue("header", "");
                }
                ////打印显示问题 系统已经要求win7以上,这个就没必要了吧?
                //pregKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION", true);
                //if (pregKey != null)
                //    pregKey.SetValue("DoubleH.exe", 9999, RegistryValueKind.DWord);

                ////加在javascript问题
                ////pregKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_LOCALMACHINE_LOCKDOWN", true);
                ////pregKey.SetValue("iexplore.exe", 0); 
                //pregKey.Dispose();
            }
            catch (Exception error)
            {
                MessageWindow.Show("注册表权限不足." + error.Message);
            }
        }
        /// <summary>
        /// 设置页边距
        /// </summary>
        /// <param name="left"></param>
        /// <param name="top"></param>
        /// <param name="right"></param>
        /// <param name="bottom"></param>
        public static void InitPrintMargin(double left, double top, double right, double bottom)
        {
            RegistryKey pregKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\PageSetup", true);
            pregKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\PageSetup", true);
            if (pregKey != null)
            {//1=25.4mm
                pregKey.SetValue("margin_bottom", bottom, RegistryValueKind.String);
                pregKey.SetValue("margin_left", left, RegistryValueKind.String);
                pregKey.SetValue("margin_right", right, RegistryValueKind.String);
                pregKey.SetValue("margin_top", top, RegistryValueKind.String);
            }
            pregKey.Dispose();
        }

        private static void CreateDirectory(params string[] directoryName)
        {
            foreach (string str in directoryName)
                if (!Directory.Exists(str))
                    Directory.CreateDirectory(str);
        }
    }
}